package cn.sinata.wanglin.publish.activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.JsonObject;
import com.hyphenate.easeui.utils.EaseSmileUtils;
import com.xilada.xldutils.activitys.ImagePagerActivity;
import com.xilada.xldutils.activitys.TitleActivity;
import com.xilada.xldutils.adapter.BaseRecyclerAdapter;
import com.xilada.xldutils.adapter.util.ViewHolder;
import com.xilada.xldutils.utils.ActivityUtil;
import com.xilada.xldutils.utils.BitmapUtils;
import com.xilada.xldutils.utils.DialogUtils;
import com.xilada.xldutils.utils.FileUtils;
import com.xilada.xldutils.utils.SharedPreferencesUtils;
import com.xilada.xldutils.utils.Utils;
import com.xilada.xldutils.xldUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.sinata.wanglin.MyApplication;
import cn.sinata.wanglin.R;
import cn.sinata.wanglin.aliyunoss.OssBean;
import cn.sinata.wanglin.aliyunoss.UpLoadImageUtils;
import cn.sinata.wanglin.commonutils.Constant;
import cn.sinata.wanglin.model.SameCityClass;
import cn.sinata.wanglin.net.HttpManager;
import cn.sinata.wanglin.net.model.util.ResultDataSubscriber;
import cn.sinata.wanglin.village.activity.EditPubWordActivity;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;

/**
 * 发布---同城八卦
 */
public class PubsamecityActivity extends TitleActivity {
    @BindView(R.id.mSwipeRefreshLayout)
    SwipeRefreshLayout mSwipeRefreshLayout ;//刷新获取分类
    @BindView(R.id.ed_content)
    EditText ed_content ;//内容
    @BindView(R.id.sc_status)
    TextView sc_status ;//是否匿名
    @BindView(R.id.sc_isCircle)
    TextView sc_isCircle ;//是否同步到圈子
    @BindView(R.id.sc_isComplaints)
    TextView sc_isComplaints ;//是否同步到小区吐槽
    @BindView(R.id.rv_towhere)
    RecyclerView rv_towhere ;//同城八卦栏目下的数据
    BaseRecyclerAdapter currentlableAdapter;
    private ArrayList<SameCityClass> mcurrentlabledatas=new ArrayList<>();
    @BindView(R.id.rv_upphoto)
    RecyclerView rv_upphoto;//所有的相册
    BaseRecyclerAdapter allphotoAdapter;
    private ArrayList<String> mImageinfos=new ArrayList<>();
    private  final int MAX_NUMBER=9;
    private boolean isPub = true;
    @Override
    protected int setContentId() {
        return R.layout.activity_pubsamecity;
    }
    @Override
    protected void initView() {
        super.initView();
        setTitle("同城八卦");
        addRightButton("提交", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                view.setEnabled(false);
                pubSaying(view);
            }
        });
        mSwipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_light, android.R.color.holo_red_light, android.R.color.holo_orange_light, android.R.color.holo_green_light);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                showDialog("获取中...");
                getClassfity();
                mSwipeRefreshLayout.setRefreshing(false);
            }
        });
        if(currentlableAdapter==null){
            GridLayoutManager mgr=new GridLayoutManager(this,4);
            rv_towhere.setLayoutManager(mgr);
            currentlableAdapter=new BaseRecyclerAdapter<SameCityClass>(mcurrentlabledatas,R.layout.item_samecitylable) {
                @Override
                public void onBind(final int position, final SameCityClass data, ViewHolder holder) {
                    holder.setText(R.id.cb_samecitylable,data.getClassify());
                    ((CheckBox)holder.bind(R.id.cb_samecitylable)).setChecked(data.isIschexked());
                    holder.bind(R.id.cb_samecitylable).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            CheckBox mCheckBox=(CheckBox)view;
                            mCheckBox.setChecked(true);
                            for(int i=0;i<mcurrentlabledatas.size();i++){
                                mcurrentlabledatas.get(i).setIschexked(false);
                            }
                            mcurrentlabledatas.get(position).setIschexked(true);
                            currentlableAdapter.notifyDataSetChanged();
                        }
                    });
                }
            };
            rv_towhere.setAdapter(currentlableAdapter);
        }
        if(allphotoAdapter==null){
            mImageinfos.add("-1");
            GridLayoutManager mgr = new GridLayoutManager(mContext, 4);
            rv_upphoto.setLayoutManager(mgr);
            allphotoAdapter= new BaseRecyclerAdapter<String>(mImageinfos, R.layout.item_myimage_grid) {
                @Override
                public void onBind(final int position, final String data, ViewHolder holder) {
                    if("-1".equals(data)){
                        ((SimpleDraweeView) holder.bind(R.id.image)).setImageURI(Uri.parse("res://mipmap/"+R.mipmap.ic_addimage));
                        holder.bind(R.id.iv_deletemyimg).setVisibility(View.GONE);
                        holder.bind(R.id.image).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                selectImages();
                            }
                        });
                    }else {
                        ((SimpleDraweeView) holder.bind(R.id.image)).setImageURI(Uri.parse("file://" + data));
                        holder.bind(R.id.iv_deletemyimg).setVisibility(View.VISIBLE);
                        holder.bind(R.id.image).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                int current=position;
                                ArrayList<String> showPhoto=new ArrayList<String>();
                                for(int i=0;i<mImageinfos.size();i++){
                                    if(!"-1".equals(mImageinfos.get(i))){
                                        showPhoto.add(mImageinfos.get(i));
                                    }else{
                                        current--;
                                    }

                                }
                                ActivityUtil.create(mContext).go(ImagePagerActivity.class)
                                        .put(ImagePagerActivity.URLS, showPhoto)
                                        .put(ImagePagerActivity.CURRENT_POSITION, current)
                                        .start();
                            }
                        });
                        holder.bind(R.id.iv_deletemyimg).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                if(mImageinfos.size()==9&&!"-1".equals(mImageinfos.get(0))){
                                    mImageinfos.remove(position);
                                    mImageinfos.add(0,"-1");
                                }else{
                                    mImageinfos.remove(position);
                                }
                                allphotoAdapter.notifyDataSetChanged();
                            }
                        });
                    }
                }
            };
            rv_upphoto.setAdapter(allphotoAdapter);
        }
        showDialog("获取中...");
        getClassfity();
    }
    /**
     * 获取到分类
     */
    private void getClassfity() {
        HttpManager.getClassify().subscribe(new ResultDataSubscriber<ArrayList<SameCityClass>>(this) {
            @Override
            public void onSuccess(String msg, ArrayList<SameCityClass> sameCityClasses) {
                if(sameCityClasses==null||sameCityClasses.size()==0){
                    return;
                }
                mcurrentlabledatas.clear();
                sameCityClasses.get(0).setIschexked(true);
                mcurrentlabledatas.addAll(sameCityClasses);
                currentlableAdapter.notifyDataSetChanged();
            }
        }
        );
    }

    /**
     * 发布内容
     */
    private void pubSaying(final View view) {
        showDialog("发布中...");
        String content=  ed_content.getText().toString().trim();
        if(TextUtils.isEmpty(content)){
            showToast("请先输入内容！");
            view.setEnabled(true);
            dismissDialog();
            return;
        }
        if(mcurrentlabledatas.size()==0){
            showToast("请先刷新获取同城八卦分类！");
            dismissDialog();
            view.setEnabled(true);
            return;
        }
        String classifyId=null;
        for(int i=0;i<mcurrentlabledatas.size();i++){
            if(mcurrentlabledatas.get(i).isIschexked()){
                classifyId=mcurrentlabledatas.get(i).getId();
            }
        }
        String  status="0";//不匿名
        if(sc_status.isSelected()){
            status="1";
        }else{
            status="0";
        }
        String  isCircle="1";//是否同步圈子 0同步 1不同步
        if(sc_isCircle.isSelected()){
            isCircle="0";
        }else{
            isCircle="1";
        }
        String  isComplaints="1";//是否同步小区吐槽 0同步 1不同步
        if(sc_isComplaints.isSelected()){
            isComplaints="0";
        }else{
            isComplaints="1";
        }
        String  isGossip="0";//是否同城八卦 0同步 1不同步


        if(mImageinfos.size()!=1){
            //有图片先上传图片。
            ArrayList<String> showPhoto=new ArrayList<String>();
            StringBuilder builder = new StringBuilder();
            for(int i=0;i<mImageinfos.size();i++){
                if(!"-1".equals(mImageinfos.get(i))){
                    BitmapUtils.Image mImage=BitmapUtils.compressImage(mImageinfos.get(i));
                    showPhoto.add(mImage.getPath());
                    builder.append(mImage.getRate());
                    builder.append(",");

                }
            }
            if (builder.length() > 1) {
                builder.deleteCharAt(builder.length()-1);
            }
            String scale = builder.toString();
            Utils.systemErr("-scale--"+scale);
            upImagesToOss(view,content,
                    status,isCircle,isComplaints,
                    isGossip, MyApplication.cityCode,classifyId,MyApplication.houseid,scale,showPhoto);
        }else{
            //没图片直接上传内容
            String userid= SharedPreferencesUtils.getString(Constant.SP_USERID);
            HttpManager.addRelease(userid,Constant.PUB_SAMECITY,content,
                    status,isCircle,isComplaints,
                    isGossip,MyApplication.cityCode,classifyId,MyApplication.houseid,null,null).subscribe(new ResultDataSubscriber<JsonObject>(PubsamecityActivity.this) {
                @Override
                public void onSuccess(String msg, JsonObject jsonObject) {
                    showToast(msg);
                    isPub = true;
                    setResult(RESULT_OK);
                    finish();
                }
                protected void onError(String code, String msg) {
                    super.onError(code, msg);
                    view.setEnabled(true);
                }
            });
        }
    }

    private void selectImages(){
        int maxnumber= MAX_NUMBER-mImageinfos.size()+1;
        ActivityUtil.create(mContext).go(MultiImageSelectorActivity.class)
                .put(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true)
                .put(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, maxnumber)
                .put(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI)
                .startForResult(3);


    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==RESULT_OK){
            if(requestCode==3&&data!=null){
                int maxnumber= MAX_NUMBER-mImageinfos.size()+1;
                ArrayList<String> resultList = new ArrayList<String>();
                resultList=data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                if(maxnumber==resultList.size()){
                    mImageinfos.remove(0);
                }
                mImageinfos.addAll(resultList);
                allphotoAdapter.notifyDataSetChanged();
            }
            if(requestCode==13&&data!=null){
                String content= data.getStringExtra("content");
                if(!TextUtils.isEmpty(content)){
                    ed_content.setText(EaseSmileUtils.getSmiledText(mContext, content));
                }else{
                    ed_content.setText("");
                }

            }
        }
    }

    private void upImagesToOss(final View view,final String content, final String status, final String isCircle, final String isComplaints, final String isGossip, final String code, final String classifyId, final String housingId, final String scale, ArrayList<String> resultList){

        final ArrayList<OssBean>  mOssBeans=new ArrayList<>();
        for (int i=0;i<resultList.size();i++){
            Utils.systemErr("-path-->"+resultList.get(i));
            mOssBeans.add(new OssBean(resultList.get(i)));
        }

        Observable<List<OssBean>> mObservable= new UpLoadImageUtils(mOssBeans).uploadimg();
        mObservable.doOnSubscribe(new Action0() {
            @Override
            public void call() {
                showDialog("上传中...");
            }
        })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<OssBean>>() {
                    @Override
                    public void onCompleted() {
                        view.setEnabled(true);
                    }
                    @Override
                    public void onError(Throwable e) {
                        dismissDialog();
                    }

                    @Override
                    public void onNext(List<OssBean> ossBeen) {
                        if(ossBeen!=null&&ossBeen.size()!=0){
                            String userid= SharedPreferencesUtils.getString(Constant.SP_USERID);
                            HttpManager.addRelease(userid,Constant.PUB_SAMECITY,content,
                                    status,isCircle,isComplaints,
                                    isGossip,code,classifyId,housingId,scale,(ArrayList<OssBean>)ossBeen).subscribe(new ResultDataSubscriber<JsonObject>(PubsamecityActivity.this) {
                                @Override
                                public void onSuccess(String msg, JsonObject jsonObject) {
                                    showToast(msg);
                                    isPub = true;
                                    setResult(RESULT_OK);
                                    finish();
                                }
                                protected void onError(String code, String msg) {
                                    super.onError(code, msg);
                                    view.setEnabled(true);
                                }
                            });
                        }
                    }
                });


    }
    @OnClick({R.id.sc_status,R.id.sc_isCircle,R.id.sc_isComplaints,R.id.ed_content})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.sc_status:
                //描述:
                boolean selected= sc_status.isSelected();
                sc_status.setSelected(!selected);
                break;
            case R.id.sc_isCircle:
                //描述:
                boolean selectedCircle= sc_isCircle.isSelected();
                sc_isCircle.setSelected(!selectedCircle);
                break;
            case R.id.sc_isComplaints:
                //描述:
                boolean selectedGossip= sc_isComplaints.isSelected();
                sc_isComplaints.setSelected(!selectedGossip);
                break;
            case R.id.ed_content:
                String  content=  ed_content.getText().toString();
                ActivityUtil.create(mContext).go(EditPubWordActivity.class)
                        .put("content",content)
                        .startForResult(13);
                break;
        }
    }

    @Override
    public void finish() {
        if(!isPub){
            DialogUtils.createNoticeDialog(mContext, "请注意", "您确定要放弃该同城八卦的发布么？", "确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dofinish();
                }
            });
        }else{
            dofinish();
        }

    }

    private void dofinish() {
        if (!TextUtils.isEmpty(xldUtils.PICDIR)) {
            FileUtils.deleteFiles(new File(xldUtils.PICDIR));
        }
        super.finish();
    }

    @Override
    public void onBackPressed() {
        if(!isPub){
            DialogUtils.createNoticeDialog(mContext, "请注意", "您确定要放弃该同城八卦的发布么？", "确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dofinish();
                }
            });
        }else{
            dofinish();
        }
    }
}
